<template>
  <div class="fulltable">
    <div class="full">
      <div class="header">
        <h2>文件管理</h2>
        <div class="upload-area">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="customUpload"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="5"
            :on-exceed="handleExceed"
            multiple>
            <el-button type="primary">上传文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传 word/pdf/excel 文件，且文件大小不超过 1GB</div>
          </el-upload>
        </div>
      </div>

      <div class="search">
        <el-input v-model="searchFileName" placeholder="输入文件名称" @input="filterFiles" clearable style="margin-right: 10px;width:200px"></el-input>
      </div>

      <el-table
        :data="filteredFiles.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
        :height="tableHeight"
        border
        style="width: 100%"
        v-loading="loading">
        <el-table-column
          prop="cFileName"
          label="文件名称"
          min-width="200"
          header-align="center"
          align="center">
        </el-table-column>
        <el-table-column
          prop="nSize"
          label="文件大小"
          width="120">
        </el-table-column>
        <el-table-column
          prop="dtUploadTime"
          label="上传时间"
          width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.dtUploadTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="cUserName"
          label="上传人"
          width="120">
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleDownload(scope.row)">下载</el-button>
            <el-button
              size="mini"
              type="danger"
              v-if="canDelete(scope.row)"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="paging">
        <el-pagination  
          @size-change="handleSizeChange"  
          @current-change="handleCurrentChange"  
          :current-page="currentPage"  
          :page-sizes="[5, 10, 20, 40, 60]"  
          :page-size="pageSize"  
          :pager-count="4"
          layout="total, sizes, prev, pager, next, jumper"  
          :total="files.length">  
        </el-pagination> 
      </div>
    </div>
  </div>
</template>

<script>
import { uploadFile, getFileList ,downloadFile,deleteFile} from '@/api/file'
import moment from 'moment'
import { jwtDecode } from 'jwt-decode'
import {addLog} from '@/api/log';
export default {
  data() {
    return {
      logItem:{
              mn:'',
              opn:'',
              res:''
      },
      files: [],
      fileList: [],
      loading: false,
      allowedTypes: ['.doc', '.docx', '.pdf', '.xls', '.xlsx','.ppt','.pptx'],
      currentPage: 1,
      pageSize: 5,
      tableHeight: 300,
      maxTableHeight: 700,
      minTableHeight: 300,
      searchFileName: '',
      userRole: this.checkUserRole(),
    }
  },
  computed: {
    filteredFiles() {
      return this.files.filter(file => {
        return file.cFileName.toLowerCase().includes(this.searchFileName.toLowerCase());
      });
    },
  },
  watch: {
    currentPage() {  
      this.calculateTableHeight()  
    },  
    pageSize() {  
      this.calculateTableHeight()  
    }
  },
  created() {
    this.getFiles()
  },
  methods: {
    // 获取文件列表
    getFiles() {
      this.loading = true
      getFileList()
        .then(response => {
          this.files = response.data
          this.calculateTableHeight() // 计算表格高度
          this.loading = false
          console.log("获取文件列表成功：",this.files)
        })
        .catch(error => {
          console.error('获取文件列表失败：', error)
          this.$message.error('获取文件列表失败')
          this.loading = false
        })
    },

    // 格式化时间
    formatDateTime(time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },

    // 上传成功后刷新列表
    customUpload({ file }) {
      const formData = new FormData()
      formData.append('file', file)
      
      this.loading = true
      uploadFile(formData)
        .then(response => {
          this.$message.success(`${file.name} 上传成功`)
          this.getFiles() // 刷新文件列表
          this.loading = false
          this.fileList = [] // 清空上传文件列表，关闭预览
      this.logItem.mn = "customUpload";
      this.logItem.opn = "上传文件-文件管理";
      this.logItem.res = "true";
      addLog(this.logItem);
        })
        .catch(error => {
          console.error('上传错误：', error)
                this.logItem.mn = "customUpload";
                this.logItem.opn = "上传文件-文件管理";
                this.logItem.res = "false";
                addLog(this.logItem);
          this.$message.error(`${file.name} 上传失败`)
          this.loading = false
        })
    },

    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        console.log("删除文件：",row.nFileId)
        deleteFile(row.nFileId)
          .then(response => {
            this.$message.success('删除成功')
            this.logItem.mn = "handleDelete";
            this.logItem.opn = "删除文件-文件管理";
            this.logItem.res = "true";
            addLog(this.logItem);
            this.getFiles() // 刷新文件列表
          })
          .catch(error => {
            this.logItem.mn = "handleDelete";
            this.logItem.opn = "删除文件-文件管理";
            this.logItem.res = "false";
            addLog(this.logItem);
            this.$message.error('删除失败：' + error.message)
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 处理下载
    handleDownload(row) {
      // 这里需要调用下载API
      downloadFile(row.nFileId).then(response => {
        const blob = new Blob([response.data])
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = row.cFileName
        link.click()
            this.logItem.mn = "handleDownload";
            this.logItem.opn = "下载文件-文件管理";
            this.logItem.res = "true";
            addLog(this.logItem);
      }).catch(() => {
            this.logItem.mn = "handleDownload";
            this.logItem.opn = "下载文件-文件管理";
            this.logItem.res = "false";
            addLog(this.logItem);
        this.$message.error('下载失败')
      })
    },

    beforeUpload(file) {
      const extension = '.' + file.name.split('.').pop().toLowerCase()
      const isAllowed = this.allowedTypes.includes(extension)
      if (!isAllowed) {
        this.$message.error('只能上传Word、PDF、PPT或Excel文件!')
        return false
      }

      const maxSize = 1024 * 1024 * 1024 // 1G
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过1G!')
        return false
      }

      return true
    },

    handleExceed(files, fileList) {
      this.$message.warning(`最多只能选择 5 个文件`)
    },

    formatFileSize(size) {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else {
        return (size / (1024 * 1024)).toFixed(2) + ' MB'
      }
    },

    handleSizeChange(val) {  
      this.pageSize = val
      this.currentPage = 1
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的文件数量-文件管理";
      this.logItem.res = "true";
      addLog(this.logItem);
      this.calculateTableHeight()
    },  
    handleCurrentChange(val) {  
      this.currentPage = val
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-文件管理";
      this.logItem.res = "true";
      addLog(this.logItem);
      this.calculateTableHeight()
    },  
    calculateTableHeight() {  
      // 获取当前页展示的数据量  
      const currentPageData = this.files.slice(
        (this.currentPage - 1) * this.pageSize, 
        this.currentPage * this.pageSize
      )
      
      // 每行高度为 50px，再加上表头高度 50px，得到总高度  
      let height = (currentPageData.length + 1) * 60 
      // 限制高度在 minTableHeight 和 maxTableHeight 之间  
      this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight))  
    },
    filterFiles() {
      // 触发计算属性更新
    },
    checkUserRole() {  
      const token = localStorage.getItem('token'); // 从本地存储获取 token  
      if (token) {  
        const decodedToken = jwtDecode(token); // 解码 token  
        return decodedToken.role; // 返回角色  
      }  
      return null; // 无 token 返回 null  
    },

    canDelete(row) {
      return this.userRole === 'SUPERMAN' || row.nUserId === this.getCurrentUser(); // 判断是否为 SUPERMAN 或上传人
    },

    getCurrentUser() {
      const token = localStorage.getItem('token');
      if (token) {
        const decodedToken = jwtDecode(token);
        return decodedToken.userId; // 假设 token 中有用户名
      }
      return null;
    },
  }
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;

}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
.paging {
  margin: 0;
  padding: 0;
  padding-top: 10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
/deep/.el-table .cell {  
  color: black;
}  
</style>